//
// Created by lau on 2019-10-17.
//
#include <jni.h>
#include "ve_core.h"
#include "graphicsengine.h"


extern "C" {

VideoEffect::GraphicsEngine *graphicsEngine = VE_NULL;

VE_Texture *generateVETexture(JNIEnv *env, jobject textureObj);

JNIEXPORT void JNICALL Java_com_lau_videoeffect_VideoEffectJni_rendFrame(
        JNIEnv *env,
        jclass,
        jobject textureInObj,
        jobject textureOutObj) {

    if (textureInObj == VE_NULL || textureOutObj == VE_NULL) {
        return;
    }

    VE_Texture *textureIn = generateVETexture(env, textureInObj);
    VE_Texture *textureOut = generateVETexture(env, textureOutObj);

    if (graphicsEngine == VE_NULL) {
        graphicsEngine = new VideoEffect::GraphicsEngine();
    }

    graphicsEngine->rendFrame(textureIn, textureOut);

}

JNIEXPORT void JNICALL Java_com_lau_videoeffect_VideoEffectJni_createContext(
        JNIEnv *env,
        jclass) {
    if (graphicsEngine == VE_NULL) {
        graphicsEngine = new VideoEffect::GraphicsEngine();
    }

    graphicsEngine->createContext();

}

VE_Texture *generateVETexture(JNIEnv *env, jobject textureObj) {
    VE_Texture *texture = new VE_Texture();
    jclass textureObjectClass = env->GetObjectClass(textureObj);

    jfieldID textureIDId = env->GetFieldID(textureObjectClass, "textureID", "I");
    texture->textureID = env->GetIntField(textureObj, textureIDId);

    jfieldID targetId = env->GetFieldID(textureObjectClass, "target", "I");
    texture->target = env->GetIntField(textureObj, targetId);

    jfieldID formatId = env->GetFieldID(textureObjectClass, "format", "I");
    texture->format = env->GetIntField(textureObj, formatId);

    jfieldID widthId = env->GetFieldID(textureObjectClass, "width", "I");
    texture->width = env->GetIntField(textureObj, widthId);

    jfieldID heightId = env->GetFieldID(textureObjectClass, "height", "I");
    texture->height = env->GetIntField(textureObj, heightId);

    env->DeleteLocalRef(textureObjectClass);
    return texture;
}

}
